﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using HSS.ServiceModel;
using System.Security.Principal;
using TestSharedData;
using System.Threading;

namespace TestWebApp
{
	public class Global : System.Web.HttpApplication
	{

		void Application_Start(object sender, EventArgs e)
		{
			VirtualServiceProvider.Initialize("chuck", false);
			VirtualServiceProvider.Register("services");
		}

		void Application_PostAuthenticateRequest(object sender, EventArgs e)
		{
			string[] roles;
			bool isAuthenticated = false;
			FormsAuthenticationTicket ticket;
			IPrincipal usr = HttpContext.Current.User;
			if (usr.Identity.IsAuthenticated && usr.Identity.AuthenticationType == "Forms")
			{
				// Authenticated User
				FormsIdentity fIdent = usr.Identity as FormsIdentity;
				ticket = fIdent.Ticket;
				isAuthenticated = usr.Identity.IsAuthenticated;
				roles = new string[] { "Everyone", "Administrators", "Custom" };
			}
			else
			{
				// Anonymous User
				ticket = new FormsAuthenticationTicket(UserIdentity.AnonymousUserName, false, 60000);
				roles = new string[] { "Guests" };
			}

			// Create a UserIdentity based on the FormsAuthenticationTicket
			UserIdentity identity = new UserIdentity(ticket, isAuthenticated);

			// Create a UserPrincipal based on the UserIdentity
			UserPrincipal principal = new UserPrincipal(identity, roles);

			// Attach the UserPrincipal to HttpContext.User and Thread.CurrentPrincipal
			HttpContext.Current.User = principal;
			Thread.CurrentPrincipal = principal;
		}

	}
}